package com.jlboot.model.po.sys;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.*;
import com.jfinal.plugin.activerecord.Record;
import com.jlboot.core.base.BaseSearchDto;
import com.jlboot.core.consts.Consts;
import com.jlboot.core.util.LoginUtil;
import com.jlboot.core.util.ModelUtil;
import com.jlboot.core.util.SearchUtil;
import com.jlboot.core.exception.JlLogicException;
import com.jlboot.model.base.sys.BaseSysApp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.text.WordUtils;

import java.util.*;

/**
 * table: sys_app
 * author: Sam
 */
@Slf4j
public class SysApp extends BaseSysApp<SysApp> {

    public static final SysApp dao = new SysApp().dao();
    public SysApp setCommon(){

        Date now=new Date();
        this.set("id",SysIdGenerator.dao.getNextId(table));
        this.set("del_tag",Consts.COMMON_NONE_DEL);
        this.set("create_time",now);
        this.set("update_time",now);
        this.set("create_by", LoginUtil.getUserId());
        this.set("update_by",LoginUtil.getUserId());
        return this;
    }

    public Page<Record> queryPage(BaseSearchDto searchDto){
        StringBuilder sqlExceptSelect=new StringBuilder("from sys_app a "
                + " where a.del_tag=? ");

        //非删除
        List<Object> list=new ArrayList<>();
        list.add(Consts.COMMON_NONE_DEL);

        for (String searchKey : searchDto.getSearch().keySet()) {

            Object searchValue=searchDto.getSearch().get(searchKey);
            boolean addSearchFlag=true;
            if(searchValue instanceof String){
                if(StrKit.isBlank(searchValue.toString())){
                    addSearchFlag=false;
                }
            }

            if(addSearchFlag){
                SearchUtil.SearchSqlObject searchSqlObject=SearchUtil.create_and_sql(searchKey,searchValue);
                sqlExceptSelect.append(searchSqlObject.getSql());
                list.addAll(searchSqlObject.getValues());
            }

        }

        //排序
        if(StrKit.isBlank(searchDto.getOrderBy())){
            sqlExceptSelect.append(" order by a.id desc ");
        }else{
            sqlExceptSelect.append(" order by ").append(searchDto.getOrderBy());
        }

        Page<Record> page= Db.paginate(searchDto.getPage()
                ,searchDto.getLimit()
                ,"select a.* ",sqlExceptSelect.toString(),list.toArray());

        return page;
    }

    public SysApp save(JSONObject data){

        SysApp obj = new SysApp();
        obj.set("app_name", data.getString("app_name"));
        obj.set("app_id", data.getString("app_id"));
        obj.set("app_secret", data.getString("app_secret"));
        obj.set("app_desc", data.getString("app_desc"));
        obj.set("status", data.getIntValue("status"));
        ModelUtil.setAddCommon(obj,table);
        obj.save();

        return obj;
    }


    public SysApp update(JSONObject data){

        String id=data.getString("id");
        if(StrKit.isBlank(id)){
            throw new JlLogicException("参数错误");
        }
        SysApp obj=dao.findById(id);
        obj.set("app_name", data.getString("app_name"));
        obj.set("app_id", data.getString("app_id"));
        obj.set("app_secret", data.getString("app_secret"));
        obj.set("app_desc", data.getString("app_desc"));
        obj.set("status", data.getIntValue("status"));
        ModelUtil.setUpdateCommon(obj);
        obj.update();

        return obj;

    }

    public void delete(String id){
        SysApp obj=SysApp.dao.findById(id);
        if(StrKit.isBlank(id)){
            throw new JlLogicException("参数错误");
        }
        if (obj == null) {
            throw new JlLogicException("记录不存在");
        } else {
            Db.tx(() -> {
                obj.delete();
                SysDeleteLog.dao.addDeleteLog(table,obj);
                return true;
            });
        }
    }

    public Integer deleteBatch(String... ids){
        List<SysApp> list=dao.find("select * from "+table+" a where del_tag=?  and "+ModelUtil.createInSql("a.id",ids)
                ,Consts.COMMON_NONE_DEL, ids);

        Integer numDelete=0;
        for (SysApp obj : list) {
            try{
                Db.tx(() -> {
                    obj.delete();
                    SysDeleteLog.dao.addDeleteLog(table,obj);
                    return true;
                });
                numDelete++;
            }catch (Exception e){
                log.error("删除失败,Table:{},Id:{}",e,table,obj.getStr("id"));
            }

        }

        return numDelete;
    }


}